﻿using KPIS.GERP.GFMS.APP.App_UI.Commons;
using KPIS.GERP.GFMS.BLL;
using KPIS.GERP.GFMS.DAL;
using KPIS.GERP.GFMS.IBLL;
using KPIS.GERP.GFMS.MODEL;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

namespace KPIS.GERP.GFMS.APP.App_UI.Forms
{
    public partial class FIM_Receives : System.Web.UI.Page
    {
        Main main = new Main();
        IBLL_FIM_Receives r = new B_FIM_Receives();
        D_FIM_Receives r2 = new D_FIM_Receives();
        IBLL_FIM_MAS_ReceiveTypes type = new B_FIM_MAS_ReceiveTypes();
        IBLL_BGM_MAS_Source source = new B_BGM_MAS_Source();
        IBLL_FIM_MAS_Contacts con = new B_FIM_MAS_Contacts();
        IBLL_HRM_PS_Employees emp = new B_HRM_PS_Employees();
        IBLL_FIM_MAS_BankAccounts acc = new B_FIM_MAS_BankAccounts();
        IBLL_FIM_MAS_Methods m = new B_FIM_MAS_Methods();
        IBLL_FIM_MAS_Banks bank = new B_FIM_MAS_Banks();
        IBLL_FIM_MAS_BankBranchs branch = new B_FIM_MAS_BankBranchs();
        IBLL_FIM_MoneyRequests mr = new B_FIM_MoneyRequests();
        IBLL_FIM_MoneyRequestDtls mrd = new B_FIM_MoneyRequestDtls();
        IBLL_FIM_MoneyReturns ret = new B_FIM_MoneyReturns();
        IBLL_FIM_MoneyReturnDtls retd = new B_FIM_MoneyReturnDtls();
        IBLL_FIM_Petitions pet = new B_FIM_Petitions();
        IBLL_ICM_Bid bid = new B_ICM_Bid();
        IBLL_ICM_Bidder bidder = new B_ICM_Bidder();
        IBLL_ICM_BidOfferCollateral bidderCol = new B_ICM_BidOfferCollateral();
        IBLL_ICM_PurchaseOrderContractCollateral poCon = new B_ICM_PurchaseOrderContractCollateral();
        IBLL_ICM_PurchaseOrderPrepayCollateral poPre = new B_ICM_PurchaseOrderPrepayCollateral();
        IBLL_BGM_ProjectOperationReport oprpt = new B_BGM_ProjectOperationReport();
        IBLL_ACM_GENERATE_ACCOUNT_Auto acm = new B_ACM_GENERATE_ACCOUNT_Auto();
        IBLL_CodeGenerate cg = new B_CodeGenerate();
        MailMerge mailMerge = new MailMerge();
        int nOffset = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && Request["do"] == "Print1")
            {
                Print1Report(Request["strReceiveSeq"], Request["strReceiptNo"], Request["strBgmSourceSeq"]);
                return;
                //Response.Redirect("FIM_Receives.aspx?do=Print1&strReceiveSeq=" + strReceiveSeq + "&strReceiptNo=" + strReceiptNo
                //+ "&strBgmSourceSeq=" + strBgmSourceSeq);
            }
            RadComboBox ddl = DropDownList_Contact1.GetComboBox();
            //DropDownList_IcmBidSeqReceive.Child = ddl;
            //DropDownList_IcmBidSeqOffer.Child = ddl;
            DropDownList_IcmPoSeqContract.Child = ddl;
            DropDownList_IcmPoSeqPrepay.Child = ddl;
            
            if (!IsPostBack)
            {
                var sysControls = main.GetSystemControls();
                var year1 = sysControls.default_bgm_year;
                int year = year1.Value;
                txtBgmYear.Text = year.ToString();
                txtBgmYear.MinValue = year - 10;
                txtBgmYear.MaxValue = year + 1;
                lblBgmYear.Text = year.ToString();

                UpdateUI1("ViewAll");

                LoadDDLFilterBgmSourceSeq();
                LoadDDLFilterReceiveType();
                ddlFilterBgmSourceSeq.SelectedIndex = 0;
                LoadDDLReceiveTypeSeq();
                LoadRBLMethodSeq();
                LoadDDLBankAccSeq();
                LoadBank();
               // DropDownList_BankBranch1.LoadRootNodes(500);
                //DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                //    , txtBgmYear.Text, true, null, null);

                rblMethodSeq.SelectedValue = "1";//เงินสด
                RblModeSelectChanged();
                rblManualReceipt_SelectedIndexChanged(null, null);
                rblMethodSeq_SelectedIndexChanged(null, null);
                CheckedChanged(null, null);
                lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            }

            if (RadGrid1.Items.Count > 0 && RadGrid1.SelectedItems.Count > 0)
            {
                cmdPrint1.Visible = true;
            }
            else
            {
                cmdPrint1.Visible = false;
            }
        }

        protected void LoadBank()
        {
            ddlBank.DataSource = bank.GetList();
            ddlBank.DataBind();
        }

        protected void LoadRadGrid1()
        {
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strRecvTypeSeq = ddlFilterReceiveType.SelectedValue;

            var data = r.GetFull(strBgmSourceSeq, null, strBgmYear,strRecvTypeSeq).OrderByDescending(o=>o.receive_seq); 
            RadGrid1.DataSource = data;

            GridSortExpression expression = new GridSortExpression();
            expression.FieldName = "receive_date";
            expression.SetSortOrder("Descending");
            RadGrid1.MasterTableView.SortExpressions.AddSortExpression(expression);

        }

        protected void LoadDDLFilterBgmSourceSeq()
        {
            ddlFilterBgmSourceSeq.DataSource = source.GetFull(true);
            ddlFilterBgmSourceSeq.DataBind();
        }

        protected void LoadDDLReceiveTypeSeq()
        {
            ddlReceiveTypeSeq.DataSource = type.GetList(ddlFilterBgmSourceSeq.SelectedValue);
            ddlReceiveTypeSeq.DataBind();

            ddlReceiveTypeSeq.SelectedIndex = 0;
            ddlReceiveTypeSeq_SelectedIndexChanged(null, null);
        }

        protected void LoadDDLFilterReceiveType()
        {
            ddlFilterReceiveType.SelectedIndex = 0;
        }

        //protected void LoadDDLCurrencySeq()
        //{
        //    ddlCurrencySeq.DataSource = cur.GetList();
        //    ddlCurrencySeq.DataBind();
        //}

        //protected void LoadDDLCurrencySeq2()
        //{
        //    ddlCurrencySeq2.DataSource = cur.GetList();
        //    ddlCurrencySeq2.DataBind();
        //}

        protected void LoadRBLMethodSeq()
        {
            var models = m.GetList();

            if (models.Count > 3)
            {
                var newModels = new List<M_FIM_MAS_Methods>();
                for (int i = 0; i < 3; i++)
                {
                    newModels.Add(models[i]);
                }
                models = newModels;    //models = (IList<M_FIM_MAS_Methods>)models.Take(3);
            }

            rblMethodSeq.DataSource = models;
            rblMethodSeq.DataBind();
        }

        protected void LoadDDLBankAccSeq()
        {
            ddlBankAccSeq.DataSource = acc.GetList(null, ddlFilterBgmSourceSeq.SelectedValue, null, null);
            ddlBankAccSeq.DataBind();
        }

        protected void ddlIcmBidSeq_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            LoadIcmBidSeq(e);
        }

        protected void ddlIcmBidSeqOffer_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            LoadIcmBidSeqOffer(e);
        }

        public void LoadIcmBidSeq(RadComboBoxItemsRequestedEventArgs e)
        {
            string strFilter = e.Text;
            string strBgmYearSeq = txtBgmYear.Text;
            string strReceiveTypeSeq = ddlReceiveTypeSeq.SelectedValue;
            //string strStep = (lblStep.Text.Length > 0 ? lblStep.Text : null);
            string strDate = dpReceiveDate.GetStringValue();
            IList<M_ICM_Bid> infolist = new List<M_ICM_Bid>();

            infolist = bid.GetReceiveList(strBgmYearSeq, strDate, strFilter);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + nOffset, infolist.Count);
            e.EndOfItems = endOffset == infolist.Count;

            for (int i = itemOffset; i < endOffset; i++)
            {
                ddlIcmBidSeq.Items.Add(new RadComboBoxItem(infolist[i].icm_bid_name, infolist[i].icm_bid_seq.ToString()));
            }

            e.Message = main.GetStatusMessage(endOffset, infolist.Count);
        }

        public void LoadIcmBidSeqOffer(RadComboBoxItemsRequestedEventArgs e)
        {
            string strFilter = e.Text;
            string strBgmYearSeq = txtBgmYear.Text;
            //string strReceiveType = (lblReceiveType.Text.Length > 0 ? lblReceiveType.Text : null);
            //string strStep = (lblStep.Text.Length > 0 ? lblStep.Text : null);
            string strDate = dpReceiveDate.GetStringValue();
            IList<M_ICM_Bid> infolist = new List<M_ICM_Bid>();

            infolist = bid.GetOfferList(strBgmYearSeq, strDate, strFilter);

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + nOffset, infolist.Count);
            e.EndOfItems = endOffset == infolist.Count;

            for (int i = itemOffset; i < endOffset; i++)
            {
                ddlIcmBidSeqOffer.Items.Add(new RadComboBoxItem(infolist[i].icm_bid_name, infolist[i].icm_bid_seq.ToString()));
            }

            e.Message = main.GetStatusMessage(endOffset, infolist.Count);
        }

        //protected void LoadDDLIcmBidSeqReceive()
        //{

        //}

        //protected void LoadDDLIcmBidSeqOffer()
        //{
        //}

        //protected void LoadDDLIcmPoSeqColatteral()
        //{
        //}

        //protected void LoadDDLIcmPoSeqPrePay()
        //{
        //}

        private void LoadRootNodes(RadTreeView treeView, TreeNodeExpandMode expandMode)
        {
            IList<M_FIM_MAS_Banks> infolist = bank.GetList();

            foreach (M_FIM_MAS_Banks info in infolist)
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.bank_name;
                node.Value = info.bank_seq.ToString();
                node.Category = "Level0";
                //node.Attributes.Add("category", "Level0");
                node.ExpandMode = expandMode;
                treeView.Nodes.Add(node);
            }
        }

        private void PopulateNodeOnDemand(RadTreeNodeEventArgs e, TreeNodeExpandMode expandMode)
        {
            IList<M_FIM_MAS_BankBranchs> infolist = branch.GetList(e.Node.Value);
            //DataTable dtb = branch.SelectTreeView(e.Node.Value);

            foreach (M_FIM_MAS_BankBranchs info in infolist)
            {
                RadTreeNode node = new RadTreeNode();
                node.Text = info.branch_name;
                node.Value = info.branch_seq.ToString();
                node.Category = "Level1";
                //if (Convert.ToInt32(row["ChildrenCount"]) > 0)
                //{
                //    node.ExpandMode = expandMode;
                //}
                e.Node.Nodes.Add(node);
            }

            e.Node.Expanded = true;
        }

        protected string GetReceiveSeq()
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                return RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["receive_seq"].Text;
            }
            else
            {
                return "";
            }
        }

        protected void UpdateUI1(string strCommand)
        {
            switch (strCommand)
            {
                case "ViewAll":
                case "Insert":
                case "Update":
                    cmdViewAll1.Visible = false;
                    cmdAddNew1.Visible = true;
                    cmdEdit1.Visible = true;
                    cmdDelete1.Visible = true;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = false;

                    PanelRadGrid1.Visible = true;
                    PanelEdit1.Visible = false;
                    break;
                case "AddNew":
                    cmdViewAll1.Visible = true;
                    cmdAddNew1.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdInsert1.Visible = true;
                    cmdUpdate1.Visible = false;

                    PanelRadGrid1.Visible = false;
                    PanelEdit1.Visible = true;

                    DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text, true, null, null);
                    DropDownList_MoneyRequest1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text, null, false, 800, null);
                    //DropDownList_IcmBidSeqReceive.LoadControl(600, null, txtBgmYear.Text, "receive", DateTime.Today.ToShortDateString());
                    //DropDownList_IcmBidSeqOffer.LoadControl(600, null, txtBgmYear.Text, "offer", DateTime.Today.ToShortDateString());
                    DropDownList_IcmPoSeqContract.LoadControl(600, null, txtBgmYear.Text);
                    DropDownList_IcmPoSeqPrepay.LoadControl(600, null, txtBgmYear.Text);
                    ddlIcmBidSeq.Enabled = true;
                    ddlIcmBidSeqOffer.Enabled = true;
                    DropDownList_IcmPoSeqContract.SetComboBoxEnable(true);
                    DropDownList_IcmPoSeqPrepay.SetComboBoxEnable(true);
                    break;
                case "Edit":
                    cmdViewAll1.Visible = true;
                    cmdAddNew1.Visible = false;
                    cmdEdit1.Visible = false;
                    cmdDelete1.Visible = false;
                    cmdInsert1.Visible = false;
                    cmdUpdate1.Visible = true;

                    PanelRadGrid1.Visible = false;
                    PanelEdit1.Visible = true;

                    DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text, true, null, null);
                    DropDownList_MoneyRequest1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue, txtBgmYear.Text, null, false, 800, null);
                    //DropDownList_IcmBidSeqReceive.LoadControl(600, null, txtBgmYear.Text, "receive", DateTime.Today.ToShortDateString());
                    //DropDownList_IcmBidSeqOffer.LoadControl(600, null, txtBgmYear.Text, "offer", DateTime.Today.ToShortDateString());
                    DropDownList_IcmPoSeqContract.LoadControl(600, null, txtBgmYear.Text);
                    DropDownList_IcmPoSeqPrepay.LoadControl(600, null, txtBgmYear.Text);
                    ddlIcmBidSeq.Enabled = false;
                    ddlIcmBidSeqOffer.Enabled = false;
                    DropDownList_IcmPoSeqContract.SetComboBoxEnable(false);
                    DropDownList_IcmPoSeqPrepay.SetComboBoxEnable(false);
                    break;
            }
        }

        protected void ClearControl1()
        {
            lblReceiveSeq.Text = "";
            //txtReceiveName.Text = "";
            txtReceiptNo.Text = "";
            DropDownList_Contact1.SetSelectedValue("");
            DropDownList_Emp1.SetSelectedValue("");
            txtTempContact.Text = "";
            txtRemarks.Text = "";
            txtAmount.Text = "";
            txtAmount2.Text = "";
            txtVatAmount.Text = "";
            txtExcludeVatAmount.Text = "";
            txtVatPercent.Text = "";
            txtTaxPercent.Text = "";
            txtTaxAmount.Text = "";
            txtIncludeVatAmount.Text = "";
            //txtBathAmount.Text = "";
            //txtBathAmount2.Text = "";
        }

        protected void RblModeSelectChanged()
        {
            string strMode = rblMode.SelectedValue;
            PanelReturn.Visible = strMode == "1";
            PanelIncome.Visible = strMode == "2";
            PanelPetition.Visible = strMode == "3";

            if (strMode == "3")
            {
                rblMethodSeq.SelectedValue = "3";
                rblMethodSeq.Enabled = false;
                rblMethodSeq_SelectedIndexChanged(null, null);
                pnReceipt.Visible = false;
            }
            else
            {
                rblMethodSeq.Enabled = true;
                pnReceipt.Visible = true;
            }

            switch (strMode)
            {
                case "1" :
                    lblModeName.Text = "รับเงินเบิกเกิน";
                    break;
                case "2" :
                    lblModeName.Text = "รับเงินรายได้";
                    break;
                case "3" :
                    lblModeName.Text = "รับจากรายการขอเบิก";
                    break;
            }
        }

        public void ddlIcmBidSeqSetSelectedValue(string strValue, string strContactSeq)
        {
            if (strValue.Length > 0)
            {
                if (ddlIcmBidSeq.FindItemByValue(strValue) == null)
                {
                    M_ICM_Bidder info = bidder.GetInfo(strValue);
                    ddlIcmBidSeq.Text = info.icm_bid_name;
                    lblIcmBidRecSeq.Text = info.icm_bid_seq.ToString();
                }
                else
                {
                    ddlIcmBidSeq.SelectedValue = strValue;
                }
            }
            else
            {
                ddlIcmBidSeq.SelectedIndex = -1;
                ddlIcmBidSeq.Text = "";
            }

            if (strContactSeq != null)
            {
                DropDownList_Contact1.SetSelectedValue(strContactSeq);
                lblContactSeq.Text = strContactSeq;
            }
            else
            {
                DropDownList_Contact1.SetSelectedValue("");
                lblContactSeq.Text = "";
            }
        }

        public void ddlIcmBidSeqOfferSetSelectedValue(string strValue, string strContactSeq)
        {
            if (strValue.Length > 0)
            {
                M_ICM_BidOfferCollateral info = bidderCol.GetInfo(strValue);

                if (ddlIcmBidSeqOffer.FindItemByValue(strValue) == null)
                {
                    ddlIcmBidSeqOffer.Text = info.icm_bid_name;
                    lblIcmBidOffColSeq.Text = info.icm_bid_seq.ToString();
                }
                else
                {
                    ddlIcmBidSeqOffer.SelectedValue = strValue;
                }
            }
            else
            {
                ddlIcmBidSeqOffer.SelectedIndex = -1;
                ddlIcmBidSeqOffer.Text = "";
            }

            if (strContactSeq != null)
            {
                DropDownList_Contact1.SetSelectedValue(strContactSeq);
                lblContactSeq.Text = strContactSeq;
            }
            else
            {
                DropDownList_Contact1.SetSelectedValue("");
                lblContactSeq.Text = "";
            }
        }

        //============================ control events ==============================

        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            hdReceiveSeq.Value = string.Empty;
            if (e.CommandName == "RowClick" && e.Item is GridDataItem)
            {
                e.Item.Selected = true;
                string strReceiveSeq = e.Item.OwnerTableView.Items[e.Item.ItemIndex]["receive_seq"].Text;
                hdReceiveSeq.Value = strReceiveSeq;
                Session["ReportSeq"] = strReceiveSeq;
            }
        }

        protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if (!e.IsFromDetailTable)
            {
                LoadRadGrid1();
            }
        }

        protected void cmdViewAll1_Click(object sender, EventArgs e)
        {
            UpdateUI1("ViewAll");
            ClearControl1();
        }

        protected void cmdAddNew1_Click(object sender, EventArgs e)
        {
            dpReceiveDate.SetValue(DateTime.Today);
            lblReceiveBy.Text = Session["EmpSeq"].ToString();
            lblReceiveByName.Text = Session["UserName"].ToString();
            rblMode.Enabled = true;

            //ddlCurrencySeq.SelectedValue = main.GetSystemControls().default_currency_seq.ToString();
            //ddlCurrencySeq2.SelectedValue = main.GetSystemControls().default_currency_seq.ToString();
            UpdateUI1("AddNew");
        }

        protected void cmdEdit1_Click(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                UpdateUI1("Edit");

                GridDataItem item = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex];
                string strReceiveSeq = main.WebString(item["receive_seq"].Text);
                string strReceiptNo = main.WebString(item["receipt_no"].Text);
                string strRefNo = main.WebString(item["ref_no"].Text);
                string strReceiveDate = main.WebString(item["receive_date"].Text);
                string strReceiveTypeSeq = main.WebString(item["receive_type_seq"].Text);
                string strManualReceipt = main.WebString(item["manual_receipt"].Text);
                string strReceiveMode = main.WebString(item["receive_mode"].Text);
                string strMethodSeq = main.WebString(item["method_seq"].Text);
                string strChequeNo = main.WebString(item["cheque_no"].Text);
                string strBranchSeq = main.WebString(item["branch_seq"].Text);
                string strBankID = main.WebString(item["bank_id"].Text);
                string strBankName = main.WebString(item["bank_name"].Text);
                string strBranchID = main.WebString(item["branch_id"].Text);
                string strBranchName = main.WebString(item["branch_name"].Text);
                string strBankAccSeq = main.WebString(item["bank_acc_seq"].Text);
                //string strBankAccNo = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["bank_acc_no"].Text;
                //string strBankAccName = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["bank_acc_name"].Text;

                string strContactSeq = main.WebString(item["contact_seq"].Text);
                string strContactName = main.WebString(item["contact_name"].Text);
                string strEmpSeq = main.WebString(item["emp_seq"].Text);
                string strEmpName = main.WebString(item["emp_name"].Text);
                string strTempContact = main.WebString(item["temp_contact"].Text);
                //string strContactPersonSeq = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["contact_person_seq"].Text;
                //string strContactPersonName = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["contact_person_seq"].Text;
                string strReceivedBy = main.WebString(item["received_by"].Text);
                string strReceivedByName = main.WebString(item["received_by_name"].Text);
                string strRemarks = main.WebString(item["remarks"].Text);

                string strIcmBidRecSeq = main.WebString(item["icm_bid_rec_seq"].Text);
                string strIcmBidOffColSeq = main.WebString(item["icm_bid_off_col_seq"].Text);
                string strIcmPoConColSeq = main.WebString(item["icm_po_con_col_seq"].Text);
                string strIcmPoPreColSeq = main.WebString(item["icm_po_pre_col_seq"].Text);
                string strIcmDnPenSeq = main.WebString(item["icm_dn_pen_seq"].Text);
                string strIcmPoInstalSeq = main.WebString(item["icm_po_instal_seq"].Text);
                string strIcmStockmmSeq = main.WebString(item["icm_stockmm_seq"].Text);

                string strPetitionSeq = main.WebString(item["petition_seq"].Text);
                string strMoneyReqSeq = main.WebString(item["money_req_seq"].Text);
                string strReciveRemark = main.WebString(item["recive_remark"].Text);
                string dTaxPercent = main.WebString(item["tax_percent"].Text);
                string dTax = main.WebString(item["tax"].Text);
                string dIncludeVat = main.WebString(item["include_vat"].Text);

                lblReceiveSeq.Text = main.WebString(strReceiveSeq);
                txtReceiptNo.Text = main.WebString(strReceiptNo);
                lblRefNo.Text = main.WebString(strRefNo);
                //txtReceiptNo.Text = main.WebString(strRefNo);
                dpReceiveDate.SetValue(main.WebString(strReceiveDate));
                ddlReceiveTypeSeq.SelectedValue = main.WebString(strReceiveTypeSeq);
                ddlReceiveTypeSeq_SelectedIndexChanged(null, null);
                rblManualReceipt.SelectedValue = main.WebString(strManualReceipt);
                rblManualReceipt_SelectedIndexChanged(null, null);
                rblMode.SelectedValue = main.WebString(strReceiveMode);
                rblMode_SelectedIndexChanged(null, null);
                rblMethodSeq.SelectedValue = main.WebString(strMethodSeq);
                rblMethodSeq_SelectedIndexChanged(null ,null);
                txtChequeNo.Text = main.WebString(strChequeNo);
                ddlBank.SelectedValue = main.WebString(strBranchSeq);
                //DropDownList_BankBranch1.SetSelectedValue(main.WebString(strBranchSeq)
                //    , main.WebString(strBankID + " : " + strBankName
                //        + " | " + strBranchID + " : " + strBranchName));
                ddlBankAccSeq.SelectedValue = main.WebString(strBankAccSeq);

                lblReceiveBy.Text = main.WebString(strReceivedBy);
                lblReceiveByName.Text = main.WebString(strReceivedByName);
                txtRemarks.Text = main.WebString(strRemarks);
                txtReciveRemark.Text = main.WebString(strReciveRemark);
                txtTaxPercent.Text = main.WebString(dTaxPercent);
                txtTaxAmount.Text = main.WebString(dTax);
                txtIncludeVatAmount.Text = main.WebString(dIncludeVat);

                //================= รอ FIMS =======================
                strIcmBidRecSeq = main.WebString(strIcmBidRecSeq);
                strIcmBidOffColSeq = main.WebString(strIcmBidOffColSeq);
                strIcmPoConColSeq = main.WebString(strIcmPoConColSeq);
                strIcmPoPreColSeq = main.WebString(strIcmPoPreColSeq);

                hIcmBidRecSeq.Text = main.WebString(strIcmBidRecSeq);
                hIcmBidOffColSeq.Text = main.WebString(strIcmBidOffColSeq);
                hIcmPoConColSeq.Text = main.WebString(strIcmPoConColSeq);
                hIcmPoPreColSeq.Text = main.WebString(strIcmPoPreColSeq);

                if (main.WebString(strIcmBidRecSeq).Length > 0)
                {

                    ddlIcmBidSeqSetSelectedValue(main.WebString(strIcmBidRecSeq), main.WebString(strContactSeq));
                    //DropDownList_Contact1.LoadControl(null, null);
                    //ddlIcmBidSeq_SelectedIndexChanged(null, null);
                }

                if (strIcmBidOffColSeq.Length > 0)
                {
                    ddlIcmBidSeqOfferSetSelectedValue(strIcmBidOffColSeq, strContactSeq);
                    ddlIcmBidSeqOffer_SelectedIndexChanged(null, null);
                }

                if (strIcmPoConColSeq.Length > 0)
                {
                    DropDownList_IcmPoSeqContract.SetSelectedValue(strIcmPoConColSeq);
                    DropDownList_IcmPoSeqContract.ddlIcmPoSeq_SelectedIndexChanged(null, null);
                }

                if (strIcmPoPreColSeq.Length > 0)
                {
                    DropDownList_IcmPoSeqPrepay.SetSelectedValue(strIcmPoPreColSeq);
                    DropDownList_IcmPoSeqPrepay.ddlIcmPoSeq_SelectedIndexChanged(null, null);
                }
                //================================================

                switch (main.WebString(strReceiveMode))
                {
                    case "1" :
                        DropDownList_MoneyRequest1.SetSelectedValue(main.WebString(strMoneyReqSeq));
                        txtAmount2.Text = main.WebString(item["amount"].Text);
                        PanelBorrow.Visible = main.WebString(item["event_seq"].Text) == "16";

                        if (PanelBorrow.Visible)
                        {
                            M_FIM_MoneyRequests mrInfo = mr.GetInfo(main.WebString(strMoneyReqSeq), main.WebString(strReceiveSeq));
                            lblReqAmount.Text = (mrInfo.total_amount != null ? mrInfo.total_amount.Value.ToString("#,##0.00") : "0.00");
                            lblReturnAmount.Text = (mrInfo.return_amount ?? 0 + mrInfo.receive_amount ?? 0).ToString("#,##0.00");
                        }

                        break;
                    case "2" :
                        if (main.WebString(strContactSeq).Length > 0)
                        {
                            rbContact.Checked = true;
                            rbEmp.Checked = false;
                            rbTemp.Checked = false;
                            CheckedChanged(null, null);
                            DropDownList_Contact1.SetSelectedValue(strContactSeq);
                        }
                        else if (main.WebString(strEmpSeq).Length > 0)
                        {
                            rbContact.Checked = false;
                            rbEmp.Checked = true;
                            rbTemp.Checked = false;
                            CheckedChanged(null, null);
                            DropDownList_Emp1.SetSelectedValue(strEmpSeq);
                        }
                        else
                        {
                            rbContact.Checked = false;
                            rbEmp.Checked = false;
                            rbTemp.Checked = true;
                            CheckedChanged(null, null);
                            txtTempContact.Text = strTempContact;
                        }
                        txtAmount.Text = main.WebString(item["amount"].Text);
                        txtVatAmount.Text = main.WebString(item["vat_amount"].Text);
                        txtExcludeVatAmount.Text = main.WebString(item["exclude_vat"].Text);
                        txtVatPercent.Text = main.WebString(item["vat_percent"].Text);

                        break;
                    case "3" :
                        DropDownList_Petition1.SetSelectedValue(main.WebString(strPetitionSeq));
                        break;
                }

                rblMode.Enabled = false;
            }
            else
            {
                main.MessageAlert(Page, "กรุณาเลือกรายการที่ต้องการแก้ไข");
            }
        }

        protected void cmdDelete1_Click(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                M_FIM_Receives info = new M_FIM_Receives();
                string strUserID = Session["EmpSeq"].ToString();
                DateTime dtNow = DateTime.Now;
                string strReceiveSeq = RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["receive_seq"].Text;

                info.receive_seq = Convert.ToInt32(strReceiveSeq);
                info.updated_by = main.ConvertNullInt(strUserID);
                info.updated_when = main.ConvertNullDateTime(dtNow);

                r.Delete(info);

                var reportInfoList = oprpt.GetFull(null, null, null, null, null, null, null, null, null, null
                    , main.ConvertNullInt(strReceiveSeq));

                foreach (var reportInfo in reportInfoList)
                {
                    reportInfo.updated_by = main.ConvertNullInt(strUserID);
                    reportInfo.updated_when = main.ConvertNullDateTime(dtNow);
                    oprpt.Delete(reportInfo);
                }

                LoadRadGrid1();
                RadGrid1.DataBind();
            }
        }

        protected void cmdInsert1_Click(object sender, EventArgs e)
        {
            M_FIM_Receives info = new M_FIM_Receives();
            string strReceiveSeq;
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strReceiptNo = txtReceiptNo.Text;
            string strReceiveDate = dpReceiveDate.GetStringValue();
            //string strReceiveTime = DateTime.Now.ToLongTimeString();
            string strReceiveTypeSeq = ddlReceiveTypeSeq.SelectedValue;
            string strManualReceipt = rblManualReceipt.SelectedValue;
            string strReceiveMode = rblMode.SelectedValue;
            string strMethodSeq = rblMethodSeq.SelectedValue;
            string strChequeNo = txtChequeNo.Text;
            string strBranchSeq = null;
            string strBankAccSeq = null;
            string strContactSeq = null; //DropDownList_Contact1.GetSelectedValue();
            string strEmpSeq = null; //DropDownList_Emp1.GetSelectedValue();
            string strTempContact = null;// txtTempContact.Text;
            string strContactPersonSeq = null;
            string strRemarks = txtRemarks.Text;
            string strReceivedBy = lblReceiveBy.Text;

            string strIcmBidRecSeq = null;
            string strIcmBidOffColSeq = null;
            string strIcmPoConColSeq = null;
            string strIcmPoPreColSeq = null;
            string strPetitionSeq = null;// DropDownList_Petition1.GetSelectedValue();
            string strMoneyReqSeq = null;// DropDownList_MoneyRequest1.GetSelectedValue();
            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;
            string strReciveRemark = txtReciveRemark.Text;
            string strSource = "Receive";

            string strAmount = "0";

            M_FIM_MAS_Contacts contInfo = new M_FIM_MAS_Contacts();
            M_FIM_MAS_Contacts contAddr = new M_FIM_MAS_Contacts();
            M_HRM_PS_Employees empInfo = new M_HRM_PS_Employees();

            lblRequireRemarks.Visible = false;

            if (r2.CheckDuplicateReceiptNo(strReceiptNo, null))
            {
                main.MessageAlert(Page, "เลขที่ใบเสร็จรับเงินซ้ำ!!");
                return;
            }

            if (strMethodSeq == "2")
                strBranchSeq = ddlBank.SelectedValue; //DropDownList_BankBranch1.GetSelectedValue();
            else if (strMethodSeq == "3")
                strBankAccSeq = ddlBankAccSeq.SelectedValue;

            switch (strReceiveMode)
            {
                case "1":
                    strMoneyReqSeq = DropDownList_MoneyRequest1.GetSelectedValue();
                    strContactSeq = (rbContact2.Checked ? lblContactSeq.Text : null);
                    strEmpSeq = (rbEmp2.Checked ? lblEmpSeq.Text : null);
                    strContactPersonSeq = (rbTemp2.Checked ? lblContactPersonSeq.Text : null);
                    strAmount = txtAmount2.Text;

                    contInfo = con.GetInfo(strContactSeq);
                    contAddr = con.GetAddressInfo(strContactSeq);
                    empInfo = emp.GetAddressInfo(strEmpSeq);

                    double dAmount = main.ConvertNullDouble(strAmount) ?? 0;
                    double dReturnedAmount = main.ConvertNullDouble(lblReturnAmount.Text) ?? 0;
                    double dRequestAmount = main.ConvertNullDouble(lblReqAmount.Text) ?? 0;
                    double dLimit = dRequestAmount * 25 / 100;

                    if (dLimit < dAmount)
                    {
                        if (string.IsNullOrEmpty(strRemarks))
                        {
                            lblRequireRemarks.Visible = true;
                            return;
                        }
                    }

                    break;
                case "2":
                    M_ICM_Bidder info1 = new M_ICM_Bidder();
                    M_ICM_PurchaseOrderContractCollateral info2 = new M_ICM_PurchaseOrderContractCollateral();
                   
                    string strIcmBidSeq = null;
                    string strIcmPoSeq = null;

                    strAmount = txtAmount.Text;
                    strContactSeq = (rbContact.Checked ? DropDownList_Contact1.GetSelectedValue() : null);
                    strEmpSeq = (rbEmp.Checked ? DropDownList_Emp1.GetSelectedValue() : null);
                    strTempContact = (rbTemp.Checked ? txtTempContact.Text : null);
                    //strIcmConSeq = (rbContact.Checked ? con.GetInfo(strContactSeq).seller_seq.ToString() : null);

                    contInfo = con.GetInfo(strContactSeq);
                    contAddr = con.GetAddressInfo(strContactSeq);
                    empInfo = emp.GetAddressInfo(strEmpSeq);

                    if (pnBidSale.Visible)
                    {
                        strIcmBidSeq = ddlIcmBidSeq.SelectedValue; 

                        info1.icm_bid_seq = main.ConvertNullInt(strIcmBidSeq);
                        info1.icm_con_seq = main.ConvertNullInt(strContactSeq);
                        info1.icm_receive_date = main.ConvertNullDateTime(strReceiveDate);
                        info1.icm_receive_time = main.ConvertNullTimeSpan(DateTime.Now);
                        // hard code----------------------
                        info1.icm_vat_seq = 2;
                        info1.vat_percent = 7;
                        info1.icm_dur_type_seq = 1;
                        info1.receive_status = "1";
                        info1.offer_status = "0";
                        info1.winner_status = "0";
                        //--------------------------------
                        info1.receive_receipt_no = strReceiptNo;
                        info1.created_by = main.ConvertNullInt(strUserID);
                        info1.created_when = main.ConvertNullDateTime(dtNow);

                        strIcmBidRecSeq = bidder.Insert(info1);
                    }

                    if (pnBidCollateral.Visible)
                    {
                        string strIcmBidderSeq = null;
                        //strIcmBidSeq = DropDownList_IcmBidSeqOffer.GetSelectedValue();
                        strIcmBidSeq = ddlIcmBidSeqOffer.SelectedValue;
                        strIcmBidderSeq = bidder.GetInfo(strIcmBidSeq, strContactSeq).icm_bidder_seq.ToString();

                        if (strIcmBidderSeq.Length > 0)
                        {
                            info1.icm_bidder_seq = Convert.ToInt32(strIcmBidderSeq);
                            info1.icm_offer_date = main.ConvertNullDateTime(strReceiveDate);
                            info1.icm_offer_time = main.ConvertNullTimeSpan(DateTime.Now);
                            info1.offer_status = "1";
                            info1.updated_by = main.ConvertNullInt(strUserID);
                            info1.updated_when = main.ConvertNullDateTime(dtNow);

                            strIcmBidOffColSeq = bidder.UpdateOffer(info1, strReceiptNo, strAmount);
                        }
                    }

                    if (pnPoContract.Visible)
                    {
                        //string strIcmPoConColSeq = null;
                        strIcmPoSeq = DropDownList_IcmPoSeqContract.GetSelectedValue();
                        //strIcmBidderSeq = bidder.GetInfo(strIcmBidSeq, strContactSeq).icm_bidder_seq.ToString();

                        if (strIcmPoSeq.Length > 0)
                        {
                            //info2.icm_po_con_col_seq = Convert.ToInt32(strIcmBidderSeq);
                            info2.icm_col_type_seq = 1;
                            info2.icm_po_con_col_amount = main.ConvertNullDouble(strAmount);
                            info2.icm_po_seq = main.ConvertNullInt(strIcmPoSeq);
                            info2.receipt_no = strReceiptNo;

                            info2.created_by = main.ConvertNullInt(strUserID);
                            info2.created_when = main.ConvertNullDateTime(dtNow);

                            strIcmPoConColSeq = poCon.Insert(info2);
                        }
                    }

                    //if (pnPoPrepay.Visible)
                    //{
                    //}

                    break;
                case "3":
                    strPetitionSeq = DropDownList_Petition1.GetSelectedValue();
                    strAmount = lblPetitionAmount.Text;
                    break;
            }

            decimal? dVatAmount = txtVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtVatAmount.Text) : 0;
            decimal? dExcludeVatAmount = dVatAmount == null || dVatAmount == 0 ? main.ConvertNullDecimal(strAmount) : main.ConvertNullDecimal(txtExcludeVatAmount.Text);
            decimal? dVatPercent = txtVatPercent.Text.Length > 0 ? main.ConvertNullDecimal(txtVatPercent.Text) : 0;
            decimal? dTax = txtTaxAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtTaxAmount.Text) : 0;
            decimal? dTaxPercent = txtTaxPercent.Text.Length > 0 ? main.ConvertNullDecimal(txtTaxPercent.Text) : 0;
            decimal? dIncludeVat = txtIncludeVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtIncludeVatAmount.Text) : 0;

            info.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
            info.bgm_year = main.ConvertNullInt(strBgmYear);
            info.receipt_no = strReceiptNo;// ;
            info.ref_no = cg.GetNextCode(TransectionType.FimReceiptNo, strBgmSourceSeq == "1" ? "1" : "2");
            info.receive_date = main.ConvertNullDateTime(strReceiveDate);
            info.receive_type_seq = main.ConvertNullInt(strReceiveTypeSeq);
            info.manual_receipt = strManualReceipt;
            info.receive_mode = strReceiveMode;
            info.method_seq = main.ConvertNullInt(strMethodSeq);
            info.cheque_no = strChequeNo;
            info.branch_seq = main.ConvertNullInt(strBranchSeq);
            info.bank_acc_seq = main.ConvertNullInt(strBankAccSeq);
            info.contact_seq = main.ConvertNullInt(strContactSeq);
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);
            //info.temp_contact = strTempContact;
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.remarks = strRemarks;
            info.amount = main.ConvertNullDouble(strAmount);

            info.received_by = main.ConvertNullInt(strReceivedBy);
            info.icm_bid_rec_seq = main.ConvertNullInt(strIcmBidRecSeq);
            info.icm_bid_off_col_seq = main.ConvertNullInt(strIcmBidOffColSeq);
            info.icm_po_con_col_seq = main.ConvertNullInt(strIcmPoConColSeq);
            info.icm_po_pre_col_seq = main.ConvertNullInt(strIcmPoPreColSeq);
            info.petition_seq = main.ConvertNullInt(strPetitionSeq);
            info.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
            info.created_by = main.ConvertNullInt(strUserID);
            info.created_when = main.ConvertNullDateTime(dtNow);

            info.vat_amount = dVatAmount;
            info.exclude_vat = dExcludeVatAmount;
            info.vat_percent = dVatPercent;
            info.recive_remark = strReciveRemark;
            info.tax = dTax;
            info.tax_percent = dTaxPercent;
            info.include_vat = dIncludeVat;
            info.source = strSource;

            //info.temp_contact = (strTempContact == null ? (contInfo.contact_name == null ? empInfo.emp_name:contInfo.contact_name) : strTempContact);
            if (strTempContact == null)
            {
                if (contInfo == null)
                {
                    if (empInfo != null)
                    {
                        info.temp_contact = empInfo.emp_name;
                    }
                    else
                    {
                        info.temp_contact = "";
                    }
                }
                else
                {
                    info.temp_contact = contInfo.contact_name;
                }
            }
            else
            {
                info.temp_contact = strTempContact;
            }

            //info.contact_address = (contAddr.address == null ? empInfo.work_area_name:contAddr.address);
            if (contAddr == null)
            {
                info.contact_address = empInfo.work_area_name;
            }
            else
            {
                info.contact_address = contAddr.address;
            }

            strReceiveSeq = r.Insert(info);

            //if (strManualReceipt == "1")
            //{
            //if (strReceiveMode == "1")
            //{
            double dReceiveAmount = Convert.ToDouble(strAmount);
            IList<M_FIM_MoneyRequestDtls> mrdInfo = mrd.GetFull(strMoneyReqSeq);
            //IList<M_FIM_MoneyReturnDtls> retdInfo = retd.GetMoneyReqDtls(null, strMoneyReqSeq);

            for (int i = 0; i < mrdInfo.Count; i++)
            {
                double dReqAmount = mrdInfo[i].amount ?? 0;
                double dReturnAmount = retd.GetList2(mrdInfo[i].money_req_dtls_seq ?? 0).Sum(o => o.amount ?? 0);//(retdInfo[i].amount != null ? retdInfo[i].amount.Value : 0);
                double dRemainAmount = dReqAmount - dReturnAmount;

                if (dRemainAmount > 0 && dReceiveAmount > 0)
                {
                    double dUsedAmount = 0;

                    if (dRemainAmount < dReceiveAmount)
                    {
                        dUsedAmount = dRemainAmount;
                        dReceiveAmount -= dRemainAmount;
                    }
                    else
                    {
                        dUsedAmount = dReceiveAmount;
                        dReceiveAmount = 0;
                    }

                    M_BGM_ProjectOperationReport reportInfo = new M_BGM_ProjectOperationReport();
                    reportInfo.bgm_proj_oper_exp_seq = mrd.GetInfo(mrdInfo[i].money_req_dtls_seq.ToString()).bgm_proj_oper_exp_seq;
                    //reportInfo.money_req_dtls_seq = expInfo.money_req_dtls_seq;
                    reportInfo.receive_seq = Convert.ToInt32(strReceiveSeq);
                    reportInfo.used_amount = dUsedAmount;
                    reportInfo.cal_amount = dUsedAmount;
                    reportInfo.rpt_type = 8;//คืนเงิน
                    reportInfo.created_by = main.ConvertNullInt(strUserID);
                    reportInfo.created_when = DateTime.Now;

                    oprpt.Insert(reportInfo);
                }
            }
            //}

            LoadRadGrid1();
            RadGrid1.DataBind();
            UpdateUI1("Insert");
            ClearControl1();
        }

        protected void cmdUpdate1_Click(object sender, EventArgs e)
        {
            M_FIM_Receives info = new M_FIM_Receives();
            string strReceiveSeq = lblReceiveSeq.Text;
            string strRefNo = lblRefNo.Text;
            string strBgmSourceSeq = ddlFilterBgmSourceSeq.SelectedValue;
            string strBgmYear = txtBgmYear.Text;
            string strReceiptNo = txtReceiptNo.Text;
            string strReceiveDate = dpReceiveDate.GetStringValue();
            string strReceiveTypeSeq = ddlReceiveTypeSeq.SelectedValue;
            string strManualReceipt = rblManualReceipt.SelectedValue;
            string strReceiveMode = rblMode.SelectedValue;
            string strMethodSeq = rblMethodSeq.SelectedValue;
            string strChequeNo = txtChequeNo.Text;
            string strBranchSeq = null;
            string strBankAccSeq = null;
            string strContactSeq = null; //DropDownList_Contact1.GetSelectedValue();
            string strEmpSeq = null; //DropDownList_Emp1.GetSelectedValue();
            string strTempContact = null;// txtTempContact.Text;
            string strContactPersonSeq = null;
            string strRemarks = txtRemarks.Text;
            string strReceivedBy = lblReceiveBy.Text;
            string strAmount = txtAmount.Text;

            string strIcmBidSeq = null;
            string strIcmBidSeqOffer = null;
            string strIcmBidRecSeq = null;
            string strIcmBidOffColSeq = null;
            string strIcmPoConColSeq = null;
            string strIcmPoPreColSeq = null;
            string strPetitionSeq = null;// DropDownList_Petition1.GetSelectedValue();
            string strMoneyReqSeq = null;// DropDownList_MoneyRequest1.GetSelectedValue();
            string strUserID = Session["EmpSeq"].ToString();
            DateTime dtNow = DateTime.Now;
            
            string strReciveRemark = txtReciveRemark.Text;

            M_FIM_MAS_Contacts contInfo = new M_FIM_MAS_Contacts();
            M_FIM_MAS_Contacts contAddr = new M_FIM_MAS_Contacts();
            M_HRM_PS_Employees empInfo = new M_HRM_PS_Employees();

            if (r2.CheckDuplicateReceiptNo(strReceiptNo, strReceiveSeq))
            {
                main.MessageAlert(Page, "เลขที่ใบเสร็จรับเงินซ้ำ!!");
                return;
            }

            if (strMethodSeq == "2")
                strBranchSeq = ddlBank.SelectedValue; //DropDownList_BankBranch1.GetSelectedValue();
            else if (strMethodSeq == "3")
                strBankAccSeq = ddlBankAccSeq.SelectedValue;

            switch (strReceiveMode)
            {
                case "1":
                    strMoneyReqSeq = DropDownList_MoneyRequest1.GetSelectedValue();
                    strContactSeq = (rbContact2.Checked ? lblContactSeq.Text : null);
                    strEmpSeq = (rbEmp2.Checked ? lblEmpSeq.Text : null);
                    strContactPersonSeq = (rbTemp2.Checked ? lblContactPersonSeq.Text : null);
                    strAmount = txtAmount2.Text;

                    contInfo = con.GetInfo(strContactSeq);
                    contAddr = con.GetAddressInfo(strContactSeq);
                    empInfo = emp.GetAddressInfo(strEmpSeq);

                    double dAmount = main.ConvertNullDouble(strAmount) ?? 0;
                    double dReturnedAmount = main.ConvertNullDouble(lblReturnAmount.Text) ?? 0;
                    double dRequestAmount = main.ConvertNullDouble(lblReqAmount.Text) ?? 0;
                    double dLimit = dRequestAmount * 25 / 100;

                    if (dLimit < dAmount)
                    {
                        if (string.IsNullOrEmpty(strRemarks))
                        {
                            lblRequireRemarks.Visible = true;
                            return;
                        }
                    }
                    break;
                case "2":
                    strAmount = txtAmount.Text;
                    strContactSeq = (rbContact.Checked ? DropDownList_Contact1.GetSelectedValue() : null);
                    strEmpSeq = (rbEmp.Checked ? DropDownList_Emp1.GetSelectedValue() : null);
                    strTempContact = (rbTemp.Checked ? txtTempContact.Text : null);
                    strIcmBidSeq = ddlIcmBidSeq.SelectedValue;
                    strIcmBidSeqOffer = ddlIcmBidSeqOffer.SelectedValue;
                    strIcmPoConColSeq = DropDownList_IcmPoSeqContract.GetSelectedValue();
                    strIcmPoPreColSeq = DropDownList_IcmPoSeqPrepay.GetSelectedValue();
                    M_ICM_Bidder info1 = new M_ICM_Bidder();
                    M_ICM_PurchaseOrderContractCollateral info2 = new M_ICM_PurchaseOrderContractCollateral();
                    M_ICM_BidOfferCollateral info3 = new M_ICM_BidOfferCollateral();

                    contInfo = con.GetInfo(strContactSeq);
                    contAddr = con.GetAddressInfo(strContactSeq);
                    empInfo = emp.GetAddressInfo(strEmpSeq);

                    if (pnBidSale.Visible)
                    {
                        //hIcmBidRecSeq.Text
                        strIcmBidRecSeq = hIcmBidRecSeq.Text;

                        info1.icm_bidder_seq = Convert.ToInt32(strIcmBidRecSeq);
                        info1.icm_bid_seq = main.ConvertNullInt(strIcmBidSeq);
                        info1.icm_con_seq = main.ConvertNullInt(strContactSeq);
                        info1.icm_receive_date = main.ConvertNullDateTime(strReceiveDate);
                        info1.icm_receive_time = main.ConvertNullTimeSpan(DateTime.Now);
                        // hard code----------------------
                        info1.icm_vat_seq = 2;
                        info1.vat_percent = 7;
                        info1.icm_dur_type_seq = 1;
                        info1.receive_status = "1";
                        info1.offer_status = "0";
                        info1.winner_status = "0";
                        //--------------------------------
                        info1.receive_receipt_no = strReceiptNo;
                        info1.created_by = main.ConvertNullInt(strUserID);
                        info1.created_when = main.ConvertNullDateTime(dtNow);

                        strIcmBidRecSeq = bidder.Insert(info1);
                    }

                    if (pnBidCollateral.Visible)
                    {
                        //string strIcmBidderSeq = null;
                        ////strIcmBidSeq = DropDownList_IcmBidSeqOffer.GetSelectedValue();
                        //strIcmBidOffColSeq = hIcmBidOffColSeq.Text;//ddlIcmBidSeqOffer.SelectedValue;
                        //strIcmBidderSeq = bidder.GetInfo(strIcmBidSeqOffer, strContactSeq).icm_bidder_seq.ToString();

                        //if (strIcmBidderSeq.Length > 0)
                        //{
                        //    info3.icm_bid_off_col_seq = Convert.ToInt32(hIcmBidOffColSeq);
                        //    info3.icm_bid_off_col_amount = strAmount;
                        //    info3.icm_bid_off_seq = "1";
                        //    info3.updated_by = main.ConvertNullInt(strUserID);
                        //    info3.updated_when = main.ConvertNullDateTime(dtNow);

                        //    bidderCol.Update(info3);
                        //}
                    }

                    if (pnPoContract.Visible)
                    {
                        ////string strIcmPoConColSeq = null;
                        //string strIcmPoSeq = DropDownList_IcmPoSeqContract.GetSelectedValue();
                        ////strIcmBidderSeq = bidder.GetInfo(strIcmBidSeq, strContactSeq).icm_bidder_seq.ToString();

                        //if (strIcmPoSeq.Length > 0)
                        //{
                        //    info2.icm_po_con_col_seq = Convert.ToInt32(hIcmPoConColSeq);
                        //    info2.icm_col_type_seq = 1;
                        //    info2.icm_po_con_col_amount = main.ConvertNullDouble(strAmount);
                        //    info2.icm_po_seq = main.ConvertNullInt(strIcmPoSeq);
                        //    info2.receipt_no = strReceiptNo;

                        //    info2.created_by = main.ConvertNullInt(strUserID);
                        //    info2.created_when = main.ConvertNullDateTime(dtNow);

                        //    strIcmPoConColSeq = poCon.Insert(info2);
                        //}
                    }

                    break;
            }

            decimal? dVatAmount = txtVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtVatAmount.Text) : 0;
            decimal? dExcludeVatAmount = dVatAmount == null || dVatAmount == 0 ? main.ConvertNullDecimal(strAmount) : main.ConvertNullDecimal(txtExcludeVatAmount.Text);
            decimal? dVatPercent = txtVatPercent.Text.Length > 0 ? main.ConvertNullDecimal(txtVatPercent.Text) : 0;
            decimal? dTax = txtTaxAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtTaxAmount.Text) : 0;
            decimal? dTaxPercent = txtTaxPercent.Text.Length > 0 ? main.ConvertNullDecimal(txtTaxPercent.Text) : 0;
            decimal? dIncludeVat = txtIncludeVatAmount.Text.Length > 0 ? main.ConvertNullDecimal(txtIncludeVatAmount.Text) : 0;

            info.receive_seq = Convert.ToInt32(strReceiveSeq);
            info.bgm_source_seq = main.ConvertNullInt(strBgmSourceSeq);
            info.bgm_year = main.ConvertNullInt(strBgmYear);
            info.receipt_no = strReceiptNo;
            info.ref_no = strRefNo;
            info.receive_date = main.ConvertNullDateTime(strReceiveDate);
            info.receive_type_seq = main.ConvertNullInt(strReceiveTypeSeq);
            info.manual_receipt = strManualReceipt;
            info.receive_mode = strReceiveMode;
            info.method_seq = main.ConvertNullInt(strMethodSeq);
            info.cheque_no = strChequeNo;
            info.branch_seq = main.ConvertNullInt(strBranchSeq);
            info.bank_acc_seq = main.ConvertNullInt(strBankAccSeq);
            info.contact_seq = main.ConvertNullInt(strContactSeq);
            info.contact_person_seq = main.ConvertNullInt(strContactPersonSeq);
            info.emp_seq = main.ConvertNullInt(strEmpSeq);
            info.temp_contact = strTempContact;
            info.remarks = strRemarks;
            info.amount = main.ConvertNullDouble(strAmount);
            //info.currency_seq = main.ConvertNullInt(strCurrencySeq);
            //info.exchange_rate = main.ConvertNullDouble(strExchangeRate);
            //info.bath_amount = main.ConvertNullDouble(strBathAmount);

            info.received_by = main.ConvertNullInt(strReceivedBy);
            info.icm_bid_rec_seq = main.ConvertNullInt(strIcmBidRecSeq);
            info.icm_bid_off_col_seq = main.ConvertNullInt(strIcmBidOffColSeq);
            info.icm_po_con_col_seq = main.ConvertNullInt(strIcmPoConColSeq);
            info.icm_po_pre_col_seq = main.ConvertNullInt(strIcmPoPreColSeq);
            info.petition_seq = main.ConvertNullInt(strPetitionSeq);
            info.money_req_seq = main.ConvertNullInt(strMoneyReqSeq);
            info.updated_by = main.ConvertNullInt(strUserID);
            info.updated_when = main.ConvertNullDateTime(dtNow);

            info.vat_amount = dVatAmount;
            info.exclude_vat = dExcludeVatAmount;
            info.vat_percent = dVatPercent;
            info.recive_remark = strReciveRemark;
            info.tax = dTax;
            info.tax_percent = dTaxPercent;
            info.include_vat = dIncludeVat;

            //info.temp_contact = (strTempContact == null ? (contInfo.contact_name == null ? empInfo.emp_name : contInfo.contact_name) : strTempContact);
            //info.contact_address = (contAddr.address == null ? empInfo.work_area_name : contAddr.address);

            if (strTempContact == null)
            {
                if (contInfo == null)
                {
                    if (empInfo != null)
                    {
                        info.temp_contact = empInfo.emp_name;
                    }
                    else
                    {
                        info.temp_contact = "";
                    }
                }
                else
                {
                    info.temp_contact = contInfo.contact_name;
                }
            }
            else
            {
                info.temp_contact = strTempContact;
            }

            if (contAddr == null)
            {
                info.contact_address = empInfo.work_area_name;
            }
            else
            {
                info.contact_address = contAddr.address;
            }

            r.Update(info);

            //if (strManualReceipt == "1")
            //{
            double dReceiveAmount = Convert.ToDouble(strAmount);
            IList<M_FIM_MoneyRequestDtls> mrdInfo = mrd.GetFull(strMoneyReqSeq);
            //IList<M_FIM_MoneyReturnDtls> retdInfo = retd.GetMoneyReqDtls(null, strMoneyReqSeq);

            for (int i = 0; i < mrdInfo.Count; i++)
            {
                double dReqAmount = mrdInfo[i].amount ?? 0;
                double dReturnAmount = retd.GetList2(mrdInfo[i].money_req_dtls_seq ?? 0).Sum(o => o.amount ?? 0);//(retdInfo[i].amount != null ? retdInfo[i].amount.Value : 0);
                double dRemainAmount = dReqAmount - dReturnAmount;

                if (dRemainAmount > 0 && dReceiveAmount > 0)
                {
                    double dUsedAmount = 0;

                    if (dRemainAmount < dReceiveAmount)
                    {
                        dUsedAmount = dRemainAmount;
                        dReceiveAmount -= dRemainAmount;
                    }
                    else
                    {
                        dUsedAmount = dReceiveAmount;
                        dReceiveAmount = 0;
                    }

                    var bgm_proj_oper_exp_seq = mrd.GetInfo(mrdInfo[i].money_req_dtls_seq.ToString()).bgm_proj_oper_exp_seq;
                    M_BGM_ProjectOperationReport reportInfo = oprpt.GetFull(null, null, null, null, null, null, null, null, null, null, Convert.ToInt32(strReceiveSeq)).Where(o => o.bgm_proj_oper_exp_seq == bgm_proj_oper_exp_seq).FirstOrDefault();

                    if (reportInfo != null)
                    {
                        reportInfo.used_amount = dUsedAmount;
                        reportInfo.cal_amount = dUsedAmount;
                        reportInfo.updated_by = main.ConvertNullInt(strUserID);
                        reportInfo.updated_when = DateTime.Now;

                        oprpt.Update(reportInfo);
                    }
                    else
                    {
                        reportInfo = new M_BGM_ProjectOperationReport();
                        reportInfo.bgm_proj_oper_exp_seq = bgm_proj_oper_exp_seq;
                        //reportInfo.money_req_dtls_seq = expInfo.money_req_dtls_seq;
                        reportInfo.receive_seq = Convert.ToInt32(strReceiveSeq);
                        reportInfo.used_amount = dUsedAmount;
                        reportInfo.cal_amount = dUsedAmount;
                        reportInfo.rpt_type = 8;//คืนเงิน
                        reportInfo.created_by = main.ConvertNullInt(strUserID);
                        reportInfo.created_when = DateTime.Now;

                        oprpt.Insert(reportInfo);
                    }

                }
            }
                //double dReceiveAmount = Convert.ToDouble(strAmount);
                ////IList<M_FIM_MoneyRequestDtls> mrdInfo = mrd.GetFull(strMoneyReqSeq);
                //IList<M_FIM_MoneyReturnDtls> retdInfo = retd.GetMoneyReqDtls(null, strMoneyReqSeq);

                //for (int i = 0; i < retdInfo.Count; i++)
                //{
                //    double dReqAmount = (retdInfo[i].req_amount != null ? retdInfo[i].req_amount.Value : 0);
                //    double dReturnAmount = (retdInfo[i].amount != null ? retdInfo[i].amount.Value : 0);
                //    double dRemainAmount = dReqAmount - dReturnAmount;

                //    if (dRemainAmount > 0 && dReceiveAmount > 0)
                //    {
                //        double dUsedAmount = 0;

                //        if (dRemainAmount < dReceiveAmount)
                //        {
                //            dUsedAmount = dRemainAmount;
                //            dReceiveAmount -= dRemainAmount;
                //        }
                //        else
                //        {
                //            dUsedAmount = dReceiveAmount;
                //            dReceiveAmount = 0;
                //        }

                //        var bgm_proj_oper_exp_seq = mrd.GetInfo(retdInfo[i].money_req_dtls_seq.ToString()).bgm_proj_oper_exp_seq;
                //        M_BGM_ProjectOperationReport reportInfo = oprpt.GetFull(null, null, null, null, null, null, null, null, null, null, Convert.ToInt32(strReceiveSeq)).Where(o => o.bgm_proj_oper_exp_seq == bgm_proj_oper_exp_seq).FirstOrDefault();

                //        if (reportInfo != null)
                //        {
                //            reportInfo.used_amount = dUsedAmount;
                //            reportInfo.cal_amount = dUsedAmount;
                //            reportInfo.updated_by = main.ConvertNullInt(strUserID);
                //            reportInfo.updated_when = DateTime.Now;

                //            oprpt.Update(reportInfo);
                //        }
                //        else
                //        {
                //            reportInfo = new M_BGM_ProjectOperationReport();
                //            reportInfo.bgm_proj_oper_exp_seq = bgm_proj_oper_exp_seq;
                //            //reportInfo.money_req_dtls_seq = expInfo.money_req_dtls_seq;
                //            reportInfo.receive_seq = Convert.ToInt32(strReceiveSeq);
                //            reportInfo.used_amount = dUsedAmount;
                //            reportInfo.cal_amount = dUsedAmount;
                //            reportInfo.rpt_type = 8;//คืนเงิน
                //            reportInfo.created_by = main.ConvertNullInt(strUserID);
                //            reportInfo.created_when = DateTime.Now;

                //            oprpt.Insert(reportInfo);
                //        }
                        
                //    }
                //}
            //}

            LoadRadGrid1();
            RadGrid1.DataBind();
            UpdateUI1("Update");
            ClearControl1();
        }

        //protected void cmdPrint1_Click(object sender, EventArgs e)
        //{
        //    string strReceiveSeq = main.WebString(RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["receive_seq"].Text);
            
        //    Response.Redirect("FIM_Receives.aspx?do=Print1&strReceiveSeq=" + strReceiveSeq);
        //}

        //private void Print1Report(string strReceiveSeq, string strReceiptNo, string strBgmSourceSeq)
        //{
        //    if (String.IsNullOrEmpty(strReceiptNo))
        //        strReceiptNo = cg.GetNextCode(TransectionType.FimReceivesReceiptNo, strBgmSourceSeq == "1" ? "1" : "2");

        //    string strUserID = Session["EmpSeq"].ToString();
        //    DateTime dtNow = DateTime.Now;
        //    M_FIM_Receives info = new M_FIM_Receives();

        //    info.receive_seq = Convert.ToInt32(strReceiveSeq);
        //    info.receipt_no = strReceiptNo;
        //    info.updated_by = main.ConvertNullInt(strUserID);
        //    info.updated_when = main.ConvertNullDateTime(dtNow);

        //    r.UpdateReceiptNo(info);
        //    //r.UpdatePrintOut(info.updated_by, null, 1, strReceiveSeq); 

        //    DataTable dtb = r.GetFullPrepare(null, null, null, null, strReceiveSeq);
        //    Dictionary<string, string> dtb1 = new Dictionary<string, string>();
        //    var employee = emp.GetInfo(Session["EmpSeq"].ToString());

        //    for (int i = 0; i < dtb.Rows.Count; i++)
        //    {
        //        DataRow dr = dtb.Rows[i];

        //        string TempContact = dr["temp_contact"].ToString();
        //        string contactAddress = dr["contact_address"].ToString();
        //        string receiveDate = dr["receive_date"].ToString();
        //        string receiveTypeName = dr["receive_type_name"].ToString();
        //        string strExcludeVat = dr["exclude_vat"].ToString();
        //        string strAmount = dr["amount"].ToString();
        //        string strVatAmount = dr["vat_amount"].ToString();

        //        dtb1.Add("C7", TempContact.ToString());
        //        dtb1.Add("C8", contactAddress);
        //        dtb1.Add("P8", receiveDate.ToString());
        //        dtb1.Add("A13", "1");
        //        dtb1.Add("C13", receiveTypeName);
        //        dtb1.Add("M13", "1");
        //        dtb1.Add("O13", strExcludeVat);
        //        dtb1.Add("R13", strExcludeVat);
        //        dtb1.Add("A24", main.MoneyTextThai(strAmount));
        //        dtb1.Add("R22", strExcludeVat);
        //        dtb1.Add("R23", strVatAmount);
        //        dtb1.Add("R24", strAmount);
        //        dtb1.Add("A28", employee.emp_name);
        //        dtb1.Add("A29", employee.job_site_name);
        //        dtb1.Add("P28", receiveDate.ToString());

        //    }
           
        //    Response.Clear();
        //    mailMerge.MergeExcel(Response, Server.MapPath("~/Reports/Templates/RETemplate.xlsx"), string.Format("ใบเสร็จรับเงิน-{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")), null, dtb1);
            
        //}

        protected void Print1Report(string ReceiveSeq,string ReceiptNo, string BgmSourceSeq)
        {
            string url = string.Format("ViewInvoiceReport.aspx?receiveseq={0}&receiptno={1}&bgmsourceseq={2}", ReceiveSeq, ReceiptNo, BgmSourceSeq);
            string s = "window.open('" + url + "', 'popup_window', 'width=750,height=600,left=100,top=100,resizable=yes');";
            ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
        }

        protected void cmdPrint1_xx_Click(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                string strReceiveSeq = main.WebString(RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["receive_seq"].Text);
                string strReceiveMode = main.WebString(RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["receive_mode"].Text);
                string strReceiveTypeSeq = main.WebString(RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["receive_type_seq"].Text);
                string strManualReceipt = main.WebString(RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["manual_receipt"].Text);
                string strBathAmount = main.WebString(RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["amount"].Text);
                string strMoneyReqSeq = main.WebString(RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["money_req_seq"].Text);
                string strReceiptNo = main.WebString(RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["receipt_no"].Text);
                string strBgmSourceSeq = main.WebString(RadGrid1.Items[RadGrid1.SelectedItems[0].ItemIndex]["bgm_source_seq"].Text);
                if (String.IsNullOrEmpty(strReceiptNo))
                    strReceiptNo = cg.GetNextCode(TransectionType.FimReceivesReceiptNo, strBgmSourceSeq == "1" ? "1" : "2");
                
                string strUserID = Session["EmpSeq"].ToString();
                DateTime dtNow = DateTime.Now;
                M_FIM_Receives info = new M_FIM_Receives();

                info.receive_seq = Convert.ToInt32(strReceiveSeq);
                info.receipt_no = strReceiptNo;
                info.updated_by = main.ConvertNullInt(strUserID);
                info.updated_when = main.ConvertNullDateTime(dtNow);
                 
                r.UpdateReceiptNo(info);

                DataTable dtb = r.GetFullPrepare(null, null, null, null, strReceiveSeq);
                Dictionary<string, string> dtb1 = new Dictionary<string, string>();
                var employee = emp.GetInfo(Session["EmpSeq"].ToString());

                for (int i = 0; i < dtb.Rows.Count; i++)
                {
                    DataRow dr = dtb.Rows[i];

                    string TempContact = dr["temp_contact"].ToString();
                    string contactAddress = dr["contact_address"].ToString();
                    DateTime? receiveDate = main.ConvertNullDateTime(dr["receive_date"]);
                    string receiveTypeName = dr["receive_type_name"].ToString();
                    string strExcludeVat = dr["exclude_vat"].ToString();
                    string strAmount = dr["amount"].ToString();
                    string strVatAmount = dr["vat_amount"].ToString();

                    dtb1.Add("C7", TempContact.ToString());
                    dtb1.Add("C8", contactAddress);
                    dtb1.Add("P8", receiveDate.ToString());
                    dtb1.Add("A13", "1");
                    dtb1.Add("C13", receiveTypeName);
                    dtb1.Add("M13", "1");
                    dtb1.Add("O13", strExcludeVat);
                    dtb1.Add("R13", strExcludeVat);
                    dtb1.Add("A24", main.MoneyTextThai(strAmount));
                    dtb1.Add("R22", strExcludeVat);
                    dtb1.Add("R23", strVatAmount);
                    dtb1.Add("R24", strAmount);
                    dtb1.Add("A28", employee.emp_name);
                    dtb1.Add("A29", employee.job_site_name);
                    dtb1.Add("P28", receiveDate.ToString());

                }

                mailMerge.MergeExcel(Response, Server.MapPath("~/Reports/Templates/RETemplate.xlsx"), string.Format("ใบเสร็จรับเงิน-{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")), null, dtb1);
                
                //var stream = new MemoryStream();
                //using (var package = new ExcelPackage(stream))
                //{
                //    // add a new worksheet to the empty workbook
                //    var worksheet = package.Workbook.Worksheets.Add("testsheet");
                //    for (int i = 0; i < dtb.Rows.Count; i++)
                //    {
                //        DataRow dr = dtb.Rows[i];

                //        worksheet.Cells[i + 1, 1].Value = i.ToString();

                //        string TempContact = dr["temp_contact"].ToString();
                //        string contactAddress = dr["contact_address"].ToString();
                //        DateTime? receiveDate = main.ConvertNullDateTime(dr["receive_date"]);
                //        string receiveTypeName = dr["receive_type_name"].ToString();
                //        string strExcludeVat = dr["exclude_vat"].ToString();
                //        string strAmount = dr["amount"].ToString();
                //        string strVatAmount = dr["vat_amount"].ToString();

                //        string strSheetName = receiveTypeName.Length == 0 ? dr["receive_type_name"].ToString() : receiveTypeName;

                //        dtb1.Add(strSheetName + "!C7", TempContact.ToString());
                //        dtb1.Add(strSheetName + "!C8", contactAddress);
                //        dtb1.Add(strSheetName + "!P8", receiveDate.ToString());
                //        dtb1.Add(strSheetName + "!A13", "1");
                //        dtb1.Add(strSheetName + "!C13", receiveTypeName);
                //        dtb1.Add(strSheetName + "!M13", "1");
                //        dtb1.Add(strSheetName + "!O13", strExcludeVat);
                //        dtb1.Add(strSheetName + "!R13", strExcludeVat);
                //        dtb1.Add(strSheetName + "!A24", main.MoneyTextThai(strAmount));
                //        dtb1.Add(strSheetName + "!R22", strExcludeVat);
                //        dtb1.Add(strSheetName + "!R23", strVatAmount);
                //        dtb1.Add(strSheetName + "!R24", strAmount);
                //        dtb1.Add(strSheetName + "!A28", employee.emp_name);
                //        dtb1.Add(strSheetName + "!A29", employee.job_site_name);
                //        dtb1.Add(strSheetName + "!P28", receiveDate.ToString()); //.HasValue ? receiveDate.Value.ToShortDateString() : "");

                //    }
                //}
                //mailMerge.MergeExcel(Response, Server.MapPath("~/App_Data/FileTemplate/RETemplate.xlsx"), string.Format("ใบเสร็จรับเงิน-{0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")), null, dtb1);

            //r.UpdatePrintOut(info.updated_by, null, 1, ""); 

                //if (strReceiveMode == "2")
                //{
                //    string strInvConnectType = type.GetInfo(strReceiveTypeSeq).inv_connect_type;

                //    switch (strInvConnectType)
                //    {
                //        case "0"://ไม่เชื่อมกับพัสดุ
                //            break;
                //        case "1"://ขายแบบ
                //            M_ICM_BidReceive info1 = new M_ICM_BidReceive();
                //            info1.icm_bid_seq = main.ConvertNullInt(strIcmBidSeq);
                //            info1.icm_con_seq = main.ConvertNullInt(strContactSeq);
                //            info1.icm_bid_rec_date = main.ConvertNullDateTime(strReceiveDate);
                //            info1.receipt_no = strReceiptNo;
                //            info1.created_by = main.ConvertNullInt(strUserID);
                //            info1.created_when = main.ConvertNullDateTime(dtNow);

                //            bidRec.Insert(info1);
                //            strIcmBidRecSeq = bidRec.SelectRecentInsertedRoleSeq();
                //            break;
                //        case "2"://ประกันซอง
                //            break;
                //        case "3"://ประกันสัญญา
                //            break;
                //        case "4"://ประกันจ่ายล่วงหน้า
                //            break;
                //        case "5"://จำหน่ายพัสดุ
                //            break;
                //    }
                //}

                //if (strManualReceipt == "0")
                //{
                //    double dReceiveAmount = Convert.ToDouble(strBathAmount);
                //    //IList<M_FIM_MoneyRequestDtls> mrdInfo = mrd.GetFull(strMoneyReqSeq);
                //    IList<M_FIM_MoneyReturnDtls> retdInfo = retd.GetMoneyReqDtls(null, strMoneyReqSeq);

                //    for (int i = 0; i < retdInfo.Count; i++)
                //    {
                //        double dReqAmount = (retdInfo[i].req_amount != null ? retdInfo[i].req_amount.Value : 0);
                //        double dReturnAmount = (retdInfo[i].amount != null ? retdInfo[i].amount.Value : 0);
                //        double dRemainAmount = dReqAmount - dReturnAmount;

                //        if (dRemainAmount > 0)
                //        {
                //            double dUsedAmount = 0;

                //            if (dRemainAmount < dReceiveAmount)
                //            {
                //                dUsedAmount = dRemainAmount;
                //                dReceiveAmount -= dRemainAmount;
                //            }
                //            else
                //            {
                //                dUsedAmount = dReceiveAmount;
                //                dReceiveAmount = 0;
                //            }

                //            var bgm_proj_oper_exp_seq = mrd.GetInfo(retdInfo[i].money_req_dtls_seq.ToString()).bgm_proj_oper_exp_seq;
                //            M_BGM_ProjectOperationReport reportInfo = oprpt.GetFull(null, null, null, null, null, null, null, null, null, null, Convert.ToInt32(strReceiveSeq)).Where(o => o.bgm_proj_oper_exp_seq == bgm_proj_oper_exp_seq).FirstOrDefault();

                //            if (reportInfo != null)
                //            {
                //                reportInfo.used_amount = dUsedAmount;
                //                reportInfo.cal_amount = dUsedAmount;
                //                reportInfo.updated_by = main.ConvertNullInt(strUserID);
                //                reportInfo.updated_when = DateTime.Now;

                //                oprpt.Update(reportInfo);
                //            }
                //            else
                //            {
                //                reportInfo = new M_BGM_ProjectOperationReport();
                //                reportInfo.bgm_proj_oper_exp_seq = bgm_proj_oper_exp_seq;
                //                //reportInfo.money_req_dtls_seq = expInfo.money_req_dtls_seq;
                //                reportInfo.receive_seq = Convert.ToInt32(strReceiveSeq);
                //                reportInfo.used_amount = dUsedAmount;
                //                reportInfo.cal_amount = dUsedAmount;
                //                reportInfo.rpt_type = 8;//คืนเงิน
                //                reportInfo.created_by = main.ConvertNullInt(strUserID);
                //                reportInfo.created_when = DateTime.Now;

                //                oprpt.Insert(reportInfo);
                //            }

                //            //M_BGM_ProjectOperationReport reportInfo = new M_BGM_ProjectOperationReport();
                //            //reportInfo.bgm_proj_oper_exp_seq = mrd.GetInfo(retdInfo[i].money_req_dtls_seq.ToString()).bgm_proj_oper_exp_seq;
                //            ////reportInfo.money_req_dtls_seq = expInfo.money_req_dtls_seq;
                //            //reportInfo.used_amount = info.bath_amount;
                //            //reportInfo.cal_amount = info.bath_amount;
                //            //reportInfo.rpt_type = 8;//คืนเงิน
                //            //reportInfo.created_by = main.ConvertNullInt(strUserID);
                //            //reportInfo.created_when = DateTime.Now;

                //            //oprpt.Insert(reportInfo);
                //        }
                //    }
                //}

                LoadRadGrid1();
                RadGrid1.DataBind();
            }
        }

        protected void ddlFilterBgmSourceSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {            
            LoadDDLFilterReceiveType();
            LoadRadGrid1();
            LoadDDLReceiveTypeSeq();
            RadGrid1.DataBind();

            lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                , txtBgmYear.Text, true, null, null);
            DropDownList_MoneyRequest1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                    , txtBgmYear.Text, null, false, null, null);

            LoadDDLBankAccSeq();
        }


        protected void ddlFilterReceiveType_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            LoadRadGrid1();
            LoadDDLReceiveTypeSeq();
            RadGrid1.DataBind();

            lblBgmSourceName.Text = ddlFilterBgmSourceSeq.SelectedItem.Text;
            DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                , txtBgmYear.Text, true, null, null);
            DropDownList_MoneyRequest1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                    , txtBgmYear.Text, null, false, null, null);

            LoadDDLBankAccSeq();
        }

        protected void txtBgmYear_TextChanged(object sender, EventArgs e)
        {
            LoadRadGrid1();
            RadGrid1.DataBind();

            lblBgmYear.Text = txtBgmYear.Text;
            DropDownList_Petition1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
                , txtBgmYear.Text, true, null, null);
            //DropDownList_MoneyRequest1.LoadControl(ddlFilterBgmSourceSeq.SelectedValue
            //    , txtBgmYear.Text, null, false, null, null);
            //DropDownList_IcmBidSeqReceive.LoadControl(600, null, txtBgmYear.Text, "receive", dpReceiveDate.GetStringValue());
            //DropDownList_IcmBidSeqOffer.LoadControl(600, null, txtBgmYear.Text, "offer", dpReceiveDate.GetStringValue());
            //DropDownList_IcmPoSeqContract.LoadControl(600, null, txtBgmYear.Text);
            //DropDownList_IcmPoSeqPrepay.LoadControl(600, null, txtBgmYear.Text);
        }

        protected void rblManualReceipt_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtReceiptNo.Enabled = rblManualReceipt.SelectedValue == "1";
        }

        protected void CheckedChanged(object sender, EventArgs e)
        {
            bool bContact = rbContact.Checked;
            bool bEmp = rbEmp.Checked;
            bool bTemp = rbTemp.Checked;

            DropDownList_Contact1.GetComboBox().Enabled = bContact;
            DropDownList_Emp1.GetComboBox().Enabled = bEmp;
            txtTempContact.Enabled = bTemp;

            DropDownList_Contact1.SetSelectedValue("");
            DropDownList_Emp1.SetSelectedValue("");
            txtTempContact.Text = "";
        }

        protected void CheckedChanged2(object sender, EventArgs e)
        {
            bool bContact2 = rbContact2.Checked;
            bool bEmp2 = rbEmp2.Checked;
            bool bTemp2 = rbTemp2.Checked;

            lblContactName.Visible = bContact2;
            lblEmpName.Visible = bEmp2;
            lblContactPersonName.Visible = bTemp2;
        }

        protected void ddlReceiveTypeSeq_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string strReceiveTypeSeq = ddlReceiveTypeSeq.SelectedValue;

            if (strReceiveTypeSeq.Length > 0)
            {
                M_FIM_MAS_ReceiveTypes info = type.GetInfo(strReceiveTypeSeq);

                switch (info.inv_connect_type)
                {
                    case "0" :
                        pnBidSale.Visible = false;
                        pnBidCollateral.Visible = false;
                        pnPoContract.Visible = false;
                        pnPoPrepay.Visible = false;
                        DropDownList_Emp1.Visible = false;
                        rbEmp.Enabled = true;
                        rbTemp.Enabled = true;
                        break;
                    case "1":
                        pnBidSale.Visible = true;
                        pnBidCollateral.Visible = false;
                        pnPoContract.Visible = false;
                        pnPoPrepay.Visible = false;
                        rbEmp.Enabled = false;
                        rbTemp.Enabled = false;
                        break;
                    case "2":
                        pnBidSale.Visible = false;
                        pnBidCollateral.Visible = true;
                        pnPoContract.Visible = false;
                        pnPoPrepay.Visible = false;
                        rbEmp.Enabled = false;
                        rbTemp.Enabled = false;
                        break;
                    case "3":
                        pnBidSale.Visible = false;
                        pnBidCollateral.Visible = false;
                        pnPoContract.Visible = true;
                        pnPoPrepay.Visible = false;
                        rbEmp.Enabled = false;
                        rbTemp.Enabled = false;
                        break;
                    case "4":
                        pnBidSale.Visible = false;
                        pnBidCollateral.Visible = false;
                        pnPoContract.Visible = false;
                        pnPoPrepay.Visible = true;
                        rbEmp.Enabled = true;
                        rbTemp.Enabled = true;
                        break;
                }
            }
        }

        protected void rblMode_SelectedIndexChanged(object sender, EventArgs e)
        {
            RblModeSelectChanged();
        }

        protected void rblMethodSeq_SelectedIndexChanged(object sender, EventArgs e)
        {
            string strMethodSeq = rblMethodSeq.SelectedValue;

            switch (strMethodSeq)
            {
                case "1" :
                    PanelCheque.Visible = false;
                    PanelTransfer.Visible = false;
                    txtReciveRemark.Visible = false;
                    break;
                case "2" :
                    PanelCheque.Visible = true;
                    PanelTransfer.Visible = false;
                    txtReciveRemark.Visible = false;
                    break;
                case "3" :
                    PanelCheque.Visible = false;
                    PanelTransfer.Visible = true;
                    txtReciveRemark.Visible = true;
                    break;
                case "4" :
                    PanelCheque.Visible = false;
                    PanelTransfer.Visible = false;
                    break;
            }
        }

        protected void treeBranchSeq_NodeExpand(object sender, RadTreeNodeEventArgs e)
        {
            PopulateNodeOnDemand(e, TreeNodeExpandMode.ServerSideCallBack);
        }

        //protected void ddlIcmBidSeqReceive_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        //{
            
        //}

        //protected void ddlIcmBidSeqOffer_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        //{

        //}

        //protected void ddlIcmPoSeqColatteral_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        //{

        //}

        //protected void ddlIcmPoSeqPrePay_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        //{

        //}

        protected void RadGrid1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (RadGrid1.SelectedItems.Count > 0)
            {
                string strReceiptNo = main.WebString(((GridDataItem)RadGrid1.SelectedItems[0])["receipt_no"].Text);

                //cmdPrint1.Enabled = strReceiptNo.Trim().Length == 0;
                //Adding on Sep 10,2014 
                hdReceiveSeq.Value = main.WebString(((GridDataItem)RadGrid1.SelectedItems[0])["receive_seq"].Text);
            }
        }

        protected void ddlBank_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(ddlBank.SelectedValue))
            {
                LoadBranch();
            }
            else
            {
                ddlBranch.DataSource = null;
                ddlBranch.DataBind();
            }
        }

        protected void LoadBranch()
        {
            if (!string.IsNullOrEmpty(ddlBank.SelectedValue))
            {
                ddlBranch.DataSource = branch.GetList(ddlBank.SelectedValue);
                ddlBranch.DataBind();
            }
            else
            {
                ddlBranch.DataSource = null;
                ddlBranch.DataBind();
            }
        }

        public void ddlIcmBidSeq_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string strValue = ddlIcmBidSeq.SelectedValue;
            DropDownList_Contact1.LoadControl(null, null);

            txtAmount.Text= bidder.AmountBidder(strValue);
        }

        public void ddlIcmBidSeqOffer_SelectedIndexChanged(object o, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            string strValue = ddlIcmBidSeqOffer.SelectedValue; 
            DropDownList_Contact1.LoadControl(null, null, "Offer", strValue);
        }

        protected void txtTaxPercent_TextChanged(object sender, EventArgs e)
        {
            CalculateTax();
        }

        protected void txtVatPercent_TextChanged(object sender, EventArgs e)
        {
            CalculateTax();
        }

        protected void txtVatAmount_TextChanged(object sender, EventArgs e)
        {
            CalculateTax();
        }

        protected void txtExcludeVatAmount_TextChanged(object sender, EventArgs e)
        {
            CalculateTax();
        }

        protected void txtIncludeVatAmount_TextChanged(object sender, EventArgs e)
        {
            CalculateTax();
        }

        protected void CalculateTax()
        {
            decimal dAmount = 0;
            decimal dVatPercent = 0;
            decimal dTaxPercent = 0;
            decimal dVatAmount = 0;
            decimal dTaxAmount = 0;
            decimal dIncludeVatAmount = 0;
            decimal dExcludeVatAmount = 0;

            if (!decimal.TryParse(txtIncludeVatAmount.Text, out dIncludeVatAmount))
            {
                return;
            }

            decimal.TryParse(txtVatPercent.Text, out dVatPercent);
            decimal.TryParse(txtTaxPercent.Text, out dTaxPercent);
            //decimal.TryParse(txtTaxPercent.Text, out dTaxPercent);

            //dExcludeVatAmount = Math.Round(dIncludeVatAmount * (100 / (100 + dVatPercent)), 2);
            decimal dPre = dIncludeVatAmount * (100 / (100 + dVatPercent));
            string[] strPre = dPre.ToString().Split('.');

            if (strPre.Length > 1 && strPre[1].Length > 2)
            {
                strPre[1] = strPre[1].Substring(0, 2);
                dPre = Convert.ToDecimal(strPre[0] + "." + strPre[1]);
            }

            dExcludeVatAmount = dPre;
            dVatAmount = dIncludeVatAmount - dExcludeVatAmount;
            dTaxAmount = dExcludeVatAmount * dTaxPercent / 100;
            dAmount = dIncludeVatAmount - dTaxAmount;

            txtVatAmount.Text = dVatAmount.ToString("#,##0.00");
            txtTaxAmount.Text = dTaxAmount.ToString("#,##0.00");
            txtAmount.Text = dAmount.ToString("#,##0.00");
            txtExcludeVatAmount.Text = dExcludeVatAmount.ToString("#,##0.00");
        }

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem dataBoundItem = e.Item as GridDataItem;
                var strSeq = dataBoundItem["receive_seq"].Text;
                GridDataItem cmditem = (GridDataItem)e.Item;
                LinkButton lbtnadd = (LinkButton)cmditem.FindControl("cmdPrintPopup");
                lbtnadd.Visible = false;
                if (!String.IsNullOrEmpty(strSeq))
                {
                    var lst = acm.GetListDetail(Convert.ToInt32(strSeq), "fim_receives");
                    if (lst.Count > 0)
                        lbtnadd.Visible = true;
                }
            }
        }

        protected void ddlRemarkTemplate_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            txtRemarks.Text = ddlRemarkTemplate.SelectedValue;
        }
        //==========================================================================

    }
}
